/*
 * Copyright 2002-2006 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.tigris.jasmincc.framework.implementation;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tigris.apexam.*;
import org.javacc.parser.*;
import org.tigris.jasmincc.framework.JavaCCStub;
import org.tigris.jasmincc.utils.SimpleFileNameFilter;

import java.io.File;

/**
 * JavaCC caller.
 * 
 * @author zhisen.huang
 * 
 */
public class JavaCCMain implements JavaCCStub {

	protected static Log logger = LogFactory.getLog(JavaCCMain.class);

	/**
	 * Create directories iteratively.
	 * 
	 * @param dir
	 */
	public static void createDirectory(String dir) throws Exception {
		StringBuffer currentDir = new StringBuffer();
		String[] directories = dir.split(String.valueOf(File.separatorChar));
		for (int i = 0; i < directories.length; i++) {
			currentDir.append(directories[i]);
			currentDir.append(String.valueOf(File.separatorChar));
			File current = new File(currentDir.toString());
			if (!current.exists() || !current.isDirectory()) {
				boolean result = current.mkdir();
				logger.info("creating dir: " + currentDir.toString());
				logger.info("created: " + result);
			}
		}
	}

	public static void deleteFiles(String d, String e) {
		SimpleFileNameFilter filter = new SimpleFileNameFilter(e);

		File dir = new File(d);
		String[] list = dir.list(filter);
		File file;
		if (list == null || list.length == 0)
			return;

		for (int i = 0; i < list.length; i++) {
			file = new File(d + list[i]);
			file.delete();
		}
	}

	protected MessageFactory messageFactory = null;

	public void compile(String[] args) throws Exception {
		logger.info(messageFactory.getMessage(this.getClass().getSimpleName()
				+ ".info", null));
		Main.mainProgram(args);
	}

	/**
	 * @param messageFactory
	 *            the messageFactory to set
	 */
	public void setMessageFactory(MessageFactory messageFactory) {
		this.messageFactory = messageFactory;
	}

}
